package com.chzye.xhanddemos

import android.app.Activity
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.util.Log
import android.widget.Toast

/**
 * USB设备连接处理Activity
 */
class UsbDeviceActivity : Activity() {
    
    companion object {
        private const val TAG = "UsbDeviceActivity"
        private const val ACTION_USB_PERMISSION = "com.chzye.xhanddemos.USB_PERMISSION"
    }
    
    private lateinit var usbManager: UsbManager
    private var pendingDevice: UsbDevice? = null
    
    private val usbReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (ACTION_USB_PERMISSION == action) {
                synchronized(this) {
                    val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        device?.let {
                            Log.d(TAG, "USB permission granted for device: ${it.deviceName}")
                            startGdActivity()
                        }
                    } else {
                        Log.d(TAG, "USB permission denied for device: ${device?.deviceName}")
                        Toast.makeText(context, "需要USB权限才能使用红外模组", Toast.LENGTH_SHORT).show()
                        finish()
                    }
                }
            }
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
        
        // 注册USB权限广播接收器
        val filter = IntentFilter(ACTION_USB_PERMISSION)
        registerReceiver(usbReceiver, filter)
        
        val action = intent.action
        Log.d(TAG, "USB device action: $action")
        
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action) {
            val device = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
            device?.let {
                Log.d(TAG, "USB device attached: ${it.deviceName}, VID: ${it.vendorId}, PID: ${it.productId}")
                
                // 检查是否是红外模组设备
                if (isInfraredDevice(it)) {
                    Log.d(TAG, "Infrared device detected")
                    pendingDevice = it
                    
                    // 检查USB权限
                    if (usbManager.hasPermission(it)) {
                        Log.d(TAG, "USB permission already granted")
                        startGdActivity()
                    } else {
                        Log.d(TAG, "Requesting USB permission")
                        requestUsbPermission(it)
                    }
                } else {
                    Log.d(TAG, "Not an infrared device, finishing activity")
                    finish()
                }
            } ?: run {
                Log.d(TAG, "No USB device found, finishing activity")
                finish()
            }
        } else {
            Log.d(TAG, "Not a USB device attached action, finishing activity")
            finish()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        try {
            unregisterReceiver(usbReceiver)
        } catch (e: Exception) {
            Log.e(TAG, "Error unregistering USB receiver: ${e.message}")
        }
    }
    
    /**
     * 申请USB权限
     */
    private fun requestUsbPermission(device: UsbDevice) {
        val permissionIntent = PendingIntent.getBroadcast(
            this, 0, Intent(ACTION_USB_PERMISSION), 
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        usbManager.requestPermission(device, permissionIntent)
    }
    
    /**
     * 启动红外摄像头Activity
     */
    private fun startGdActivity() {
        Log.d(TAG, "Starting GdActivityJava")
        val gdIntent = Intent(this, GdActivityJava::class.java)
        gdIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(gdIntent)
        finish()
    }
    
    /**
     * 判断是否是红外设备
     */
    private fun isInfraredDevice(device: UsbDevice): Boolean {
        // 检查设备类别
        return device.deviceClass == 14 || // UVC设备类
               device.deviceClass == 239 || // 红外设备类
               device.deviceName.contains("infrared", ignoreCase = true) ||
               device.deviceName.contains("thermal", ignoreCase = true)
    }
}